//
//  XZApplyToJoinGroupVC.m
//  Teecloud
//
//  Created by PC on 2018/11/15.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "XZApplyToJoinGroupVC.h"
#import "XZMyGroupVC.h"
#import "FSTextView.h"
#import "GMPhotoCell.h"
#import "TZImagePickerController.h"
#import <KSPhotoBrowser/KSPhotoBrowser.h>
#import "ZJPickBaseView.h"
#import "ZJDatePickerView.h"
#import "ZJNormalPickerView.h"
#import "GMFileModel.h"
@interface XZApplyToJoinGroupVC ()<UICollectionViewDataSource,UICollectionViewDelegate,XMGWaterflowLayoutDelegate,TZImagePickerControllerDelegate,UITextViewDelegate>
@property (nonatomic, strong) NSMutableArray *imgArr;
@property (nonatomic, strong) NSMutableArray *netImgArr;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet FSTextView *textView;
@property (weak, nonatomic) IBOutlet UIView *bagView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *birthdayLabel;
//最多个数选择图片
@property(nonatomic,assign)NSInteger maxCount;
@end

@implementation XZApplyToJoinGroupVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"申请加入";
    self.view.backgroundColor = kWhiteColor;
    [self setTextView];
}
- (void)setTextView{
    self.maxCount = 5;
    [self.collectionView registerNib:[UINib nibWithNibName:@"GMPhotoCell" bundle:nil] forCellWithReuseIdentifier:@"GMPhotoCell"];
    //设置FSTextView的属性
    _textView.placeholder = @"不得少于20个字（可以在下方提交相关资质/荣誉证书图片）";
    _textView.placeholderColor = [UIColor colorWithHexString:@"8C8C8C" andAlpha:1.0];
    _textView.placeholderFont = [UIFont systemFontOfSize:14];
    _textView.canPerformAction = NO;
    _textView.delegate = self;
    _textView.textColor = kDarkGrayColor;
    _textView.backgroundColor = kWhiteColor;
    _textView.tintColor = kDarkGrayColor;
    _textView.layer.borderWidth = 0.5;
    _textView.layer.borderColor = kD7D7D7Color.CGColor;
    _textView.maxLength = 500;//限制输入最大字符数.
}

- (NSMutableArray *)netImgArr{
    if (!_netImgArr) {
        _netImgArr = [[NSMutableArray alloc]init];
    }
    return _netImgArr;
}
-(NSMutableArray *)imgArr{
    if (!_imgArr) {
        _imgArr = [[NSMutableArray alloc] init];
    }
    return _imgArr;
}
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        //1.初始化layout
        // 创建布局
        XMGWaterflowLayout *layout = [[XMGWaterflowLayout alloc] init];
        layout.delegate = self;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH-20, 80) collectionViewLayout:layout];
        _collectionView.backgroundColor = kWhiteColor;
        _collectionView.dataSource = self;
        _collectionView.scrollEnabled = NO;
        _collectionView.delegate = self;
        [self.bagView addSubview:_collectionView];
        
    }
    return _collectionView;
}
//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.imgArr.count+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    GMPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GMPhotoCell" forIndexPath:indexPath];
    if (indexPath.row == self.imgArr.count || self.imgArr.count == 0) {
        cell.photoImg.image = [UIImage imageNamed:@"photo_add"];
        cell.delectBtn.hidden=YES;
    }else{
        cell.photoImg.image =self.imgArr[indexPath.row];
        cell.delectBtn.hidden=NO;
        cell.delectBtn.tag = indexPath.row +1000;
        [cell.delectBtn addTarget:self action:@selector(delectImageWithBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return cell;
}
#pragma mark - <XMGWaterflowLayoutDelegate>
- (CGFloat)waterflowLayout:(XMGWaterflowLayout *)waterflowLayout heightForItemAtIndex:(NSUInteger)index itemWidth:(CGFloat)itemWidth{
    //计算item的高度
    return itemWidth;
}

- (CGFloat)rowMarginInWaterflowLayout:(XMGWaterflowLayout *)waterflowLayout{
    return 10;
}
/**返回每行的个数*/
- (CGFloat)columnCountInWaterflowLayout:(XMGWaterflowLayout *)waterflowLayout{
    return 5;
}

- (UIEdgeInsets)edgeInsetsInWaterflowLayout:(XMGWaterflowLayout *)waterflowLayout{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

//点击item方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    if (indexPath.row == self.imgArr.count) {
        
        //显示弹出框列表选择
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
                                                                       message:nil
                                                                preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                             handler:^(UIAlertAction * action) {
                                                                 //响应事件
                                                                 NSLog(@"action = %@", action);
                                                             }];
        
        UIAlertAction* womanAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault
                                                            handler:^(UIAlertAction * action) {
                                                                //响应事件
                                                                TZImagePickerController *pickerController = [[TZImagePickerController alloc]initWithMaxImagesCount:self.maxCount - self.imgArr.count delegate:self];
                                                                pickerController.sortAscendingByModificationDate = NO;
                                                                kWeakObject(self)
                                                                [pickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photo, NSArray *assets, BOOL isSelectOriginalPhoto){
                                                                    
                                                                    if (photo.count) {
                                                                        [weakself addNewImages:photo];
                                                                    }
                                                                }];
                                                                [self presentViewController:pickerController animated:YES completion:nil];
                                                            }];
        [alert addAction:cancelAction];
        [alert addAction:womanAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    }else{
        /**放大图片*/
        GMPhotoCell * cell = (GMPhotoCell *)[self collectionView:collectionView cellForItemAtIndexPath:indexPath];//即为要得到的cell
        NSMutableArray *items = @[].mutableCopy;
        NSInteger count = self.imgArr.count;
        for (int i = 0; i < count; i++) {
            UIImageView *imgV = cell.photoImg;
            KSPhotoItem *item = [KSPhotoItem itemWithSourceView:imgV image:self.imgArr[i]];
            [items addObject:item];
        }
        
        KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:items selectedIndex:indexPath.row];
        browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleRotation;
        browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlurPhoto;
        browser.loadingStyle = KSPhotoBrowserImageLoadingStyleDeterminate;
        browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleDot;
        browser.bounces = NO;
        [browser showFromViewController:self];
    }
    
    
}
//添加多张图片--
-(void)addNewImages:(NSArray *)newImages{
    
    //默认多张图片选择顺序是按照用户选择顺序，所以这里进行反序，因为后面把刚添加的index 置为0；
    NSArray* images = [[newImages reverseObjectEnumerator] allObjects];
    [images enumerateObjectsUsingBlock:^(UIImage * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.imgArr insertObject:obj atIndex:0];
        
    }];
    [self.collectionView reloadData];
    //先从服务器获取OSS需要的数据
    
}
#pragma mark --- <UIImagePickerControllerDelegate>
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    UIImage *image = info[@"UIImagePickerControllerOriginalImage"];
    [picker dismissViewControllerAnimated:YES completion:nil];
    if (image) {
        [self addNewImage:image];
    }
}
-(void)addNewImage:(UIImage *)newImage{
    
    [self.imgArr insertObject:newImage atIndex:0];
    [self.collectionView reloadData];
    
}
- (void)delectImageWithBtn:(UIButton *)sender{
    NSInteger index =sender.tag -1000;
    [self.imgArr removeObjectAtIndex:index];
    [self.collectionView reloadData];
}
//真实姓名
- (IBAction)nameViewTagAction:(UITapGestureRecognizer *)sender {
    //创建一个弹框
    UIAlertController *addAlertVC = [UIAlertController alertControllerWithTitle:@"请输入您的真实姓名" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    //创建两个textFiled输入框
    [addAlertVC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入您的真实姓名";
    }];
    //创建取消事件(按钮)
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    //添加 取消事件 到 弹窗界面
    [addAlertVC addAction:cancelAction];
    //创建 确认按钮(事件) 并添加到弹窗界面
    kWeakObject(self)
    UIAlertAction *confirmAction =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        weakself.nameLabel.text = addAlertVC.textFields.firstObject.text;
    }];
    [addAlertVC addAction:confirmAction];
    //模态显示一个弹框  注意: UIAlterController只能通过模态形式进行弹出,不能使用push
    [self.navigationController presentViewController:addAlertVC animated:NO completion:nil];
}
//出生日期
- (IBAction)birthdayViewTapAction:(UITapGestureRecognizer *)sender {
    kWeakObject(self)
    [self.textView resignFirstResponder];
    [ZJDatePickerView zj_showDatePickerWithTitle:@"请选择出生日期" dateType:ZJDatePickerModeYMD defaultSelValue:nil minDate:nil maxDate:nil isAutoSelect:YES lineColor:kDarkGrayColor rowHeight:40 resultBlock:^(NSString *selectValue) {
        weakself.birthdayLabel.text = selectValue;
    } cancelBlock:^{
        
    }];
}
//提交
- (IBAction)submitButtonAction:(UIButton *)sender {
    if ([self.nameLabel.text isEqualToString:@"未设置"]) {
        [MBProgressHUD showErrorOrSuc:@"请填写真实姓名" toView:self.view];
        return;
    }
    if ([self.birthdayLabel.text isEqualToString:@"未设置"]) {
        [MBProgressHUD showErrorOrSuc:@"请选择出生日期" toView:self.view];
        return;
    }
    if (kIsEmptyString(self.textView.text)) {
        [MBProgressHUD showErrorOrSuc:@"请填写自我介绍" toView:self.view];
        return;
    }
    
    if (self.textView.text.length < 20) {
        [MBProgressHUD showErrorOrSuc:@"自我介绍不得少于20个字" toView:self.view];
        return;
    }
    
    //有图片的话先上传图片
    dispatch_group_t uploadGroup = dispatch_group_create();
    for (NSInteger i =0; i<self.imgArr.count; i++) {
        dispatch_group_enter(uploadGroup);
        NSDictionary *dict= @{@"from":FROM_IOS,
                              @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                              @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                              @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                              @"fileType":@"res-remark"
                              };
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        NSData *imageData = UIImageJPEGRepresentation(self.imgArr[i], 0.5);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
        [HJNetwork uploadImageURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=UploadFile&$v=%@",VERSION] parameters:dict imageData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg" progress:^(NSProgress *progress) {
            
        } callback:^(id responseObject, NSError *error) {
            if (!error) {
                if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]){
                    GMFileModel *model = [GMFileModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                    [self.netImgArr addObject:model];
                    dispatch_group_leave(uploadGroup);
                }else{
                    /**显示错误信息*/
                    [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:self.view];
                }
            }
        }];
    }
    dispatch_group_notify(uploadGroup, dispatch_get_main_queue(), ^{
        [self PostGroupApply];
    });
}

//提交
- (void)PostGroupApply{
    NSString *imgFile1Id =@"";
    NSString *imgFile2Id =@"";
    NSString *imgFile3Id =@"";
    NSString *imgFile4Id =@"";
    NSString *imgFile5Id =@"";
    for (NSInteger i=0; i<self.netImgArr.count; i++) {
        GMFileModel *model =self.netImgArr[i];
        switch (i) {
            case 0:{
                imgFile1Id =model.Id;
            }
                break;
            case 1:{
                imgFile2Id =model.Id;
            }
                break;
            case 2:{
                imgFile3Id =model.Id;
            }
                break;
            case 3:{
                imgFile4Id =model.Id;
            }
                break;
            case 4:{
                imgFile5Id =model.Id;
            }
                break;
            default:
                break;
        }
    }
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    //社团/小组id
    [dict setValue:self.groupId forKey:@"groupId"];
    /*姓名 出生年月 自我介绍*/
    [dict setValue:self.nameLabel.text forKey:@"name"];
    [dict setValue:self.textView.text forKey:@"content"];
    [dict setValue:self.birthdayLabel.text forKey:@"birthDate"];
    
    
    //图片地址
    [dict setValue:imgFile1Id forKey:@"imgFile1Id"];
    [dict setValue:imgFile2Id forKey:@"imgFile2Id"];
    [dict setValue:imgFile3Id forKey:@"imgFile3Id"];
    [dict setValue:imgFile4Id forKey:@"imgFile4Id"];
    [dict setValue:imgFile5Id forKey:@"imgFile5Id"];
    kWeakObject(self)http:
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=PostGroupApply&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSString *msg =[responseObject objectForKey:RESULT_NAME_Message];
                if (msg != nil) {
                  [MBProgressHUD showErrorOrSuc:msg toView:weakself.view];
                }
//                [weakself.navigationController popViewControllerAnimated:true];
                XZMyGroupVC *myGroupVC = [[XZMyGroupVC alloc]init];
                myGroupVC.isJoinVC = YES;
                [weakself.navigationController pushViewController:myGroupVC animated:true];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络出错" toView:weakself.view];
        }
    }];
}

@end
